﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System.Threading;
using work_log.FileService;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace work_log {
    public partial class frmFiles : DevExpress.XtraEditors.XtraForm {
        /// <summary>
        /// 获取当前UI线程
        /// </summary>
        SynchronizationContext fileContext = null;
        Thread fileThread = null;
        Guid fId = Guid.Empty;
        public frmFiles() {
            InitializeComponent();
            fileContext = SynchronizationContext.Current;
        }

        private void frmFiles_Load(object sender, EventArgs e) {
            this.gridView1.MouseDown += gridView1_MouseDown;
            this.gridView1.CustomDrawRowIndicator += gridView1_CustomDrawRowIndicator;

            this.gridView1.IndicatorWidth = 40;

            this.progressPanel1.Visible = true;
        }

        #region GridView Opertion
        void gridView1_MouseDown(object sender, MouseEventArgs e) {
            GridHitInfo hInfo = gridView1.CalcHitInfo(new Point(e.X, e.Y));
            if (e.Button == System.Windows.Forms.MouseButtons.Left && e.Clicks == 2) {
                if (hInfo.InRow) {
                    fId = Guid.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FId").ToString());
                    //fileThread = new Thread(new ThreadStart(this.Download));
                    //fileThread.Start();
                    Download();
                }
            }
        }

        void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e) {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0) {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        #endregion

        #region InitData
        private void Init() {
            try {
                FileService.ResultInfoOfFileLogs result = new FileService.FileLogsServicesSoapClient().FindByWId(WorkLogInfo.wId);
                if (result.Result) {
                    fileContext.Post(FileSafeOpertion, result.DataFormat);
                } else {
                    XtraMessageBox.Show(result.MSG);
                }
            } catch (Exception) {
                XtraMessageBox.Show("未能连接到数据服务器，请重新尝试...");
            }
            fileContext.Post(FileSafeOpertion, null);
        }
        #endregion

        #region Thread Opertion
        private void FileSafeOpertion(object text) {
            if (text != null) {
                MemoryStream ms = new MemoryStream((byte[])text);
                IFormatter formatData = new BinaryFormatter();
                gridControl1.DataSource = (DataTable)formatData.Deserialize(ms);
            } else {
                this.progressPanel1.Visible = false;
            }
        }
        #endregion

        #region CustomOpertion
        private void Download() {
            try {
                ResultInfoOfFileLogs result = new FileLogsServicesSoapClient().FindByFId(fId);
                if (result.Result) {
                    FolderBrowserDialog saveDailog = new FolderBrowserDialog();
                    if (saveDailog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                        byte[] files = result.Data.FFile;
                        string path = saveDailog.SelectedPath.ToString();
                        if (path != "") {
                            BinaryWriter bw = new BinaryWriter(File.Open(path + "\\" + result.Data.FName + result.Data.FExtiend, FileMode.OpenOrCreate));
                            bw.Write(files);
                            bw.Close();
                        }
                        XtraMessageBox.Show("下载成功！");
                    }
                }
            } catch (Exception) {
                XtraMessageBox.Show("未能连接到数据服务器，请重新尝试...");
            }
        }
        #endregion

        private void frmFiles_Shown(object sender, EventArgs e) {
            fileThread = new Thread(new ThreadStart(this.Init));
            fileThread.Start();
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                if (this.gridView1.RowCount > 0) {
                    Guid FId = Guid.Parse(this.gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FId").ToString());
                    if (XtraMessageBox.Show("是否确认删除？", "温馨提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK) {
                        ResultInfoOfFileLogs result = new FileLogsServicesSoapClient().Del(FId);
                        if (result.Result) {
                            XtraMessageBox.Show(result.MSG);
                            fileThread = new Thread(new ThreadStart(this.Init));
                            fileThread.Start();
                        } else {
                            XtraMessageBox.Show(result.MSG);
                        }
                    }
                }
            } catch (Exception ex) {
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void 重新加载ToolStripMenuItem_Click(object sender, EventArgs e) {
            if (!this.progressPanel1.Visible) {
                this.progressPanel1.Visible = true;
                fileThread = new Thread(new ThreadStart(this.Init));
                fileThread.Start();
            } else {
                XtraMessageBox.Show("当前正在获取数据，请不要重复获取！");
            }
        }
    }
}